<?php

namespace app\api\model;

use addons\epay\library\Service;
use think\Db;
use think\Model;
use Yansongda\Pay\Exceptions\GatewayException;

class OrderUnion extends Model
{
    protected $name = 'order_union';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';


    /**
     * @ 支付
     * @param string $orderid
     * @param int    $user_id
     * @param string $paytype
     * @param string $method
     * @param string $openid
     * @param string $notifyurl
     * @param string $returnurl
     * @return \addons\epay\library\Collection|\addons\epay\library\RedirectResponse|\addons\epay\library\Response|null
     * @throws \Exception
     */
    public static function pay($order_sn, $user_id, $paytype, $method = 'web', $openid = '', $notifyurl = null, $returnurl = null)
    {
        $request = \think\Request::instance();
        $order = OrderUnion::get(['order_sn'=>$order_sn,'user_id'=>$user_id]);

        if (!$order) {
            throw new \Exception('订单不存在！');
        }
        if ($order->pay_status) {
            throw new \Exception('订单已支付！');
        }
        if ($order->orderstate) {
            throw new \Exception('订单已失效！');
        }
        //支付金额为0，无需支付
        if ($order->saleamount == 0) {
            throw new \Exception('无需支付！');
        }
        $order_sn = $order->order_sn;
        /*// 启动事务
        Db::startTrans();
        try {
            //支付方式变更
            //更新支付类型和方法
            $order->save(['paytype' => $paytype]);
            //提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new \Exception($e->getMessage());
        }*/
        $response = null;
        $epay = get_addon_info('epay');

        if ($epay && $epay['state']) {

            $notifyurl = $notifyurl ? $notifyurl : $request->root(true) . '/api/order/epay/type/notify/paytype/' . $paytype;
            $returnurl = $returnurl ? $returnurl : $request->root(true) . '/api/order/epay/type/return/paytype/' . $paytype . '/order_sn/' . $order_sn;

            //保证取出的金额一致，不一致将导致订单重复错误
            $amount = sprintf("%.2f", $order->saleamount);

            $params = [
                'amount'    => $amount,
                'orderid'   => $order_sn,
                'type'      => $paytype,
                'title'     => "支付{$amount}元",
                'notifyurl' => $notifyurl,
                'returnurl' => $returnurl,
                'method'    => $method,
                'openid'    => $openid
            ];

            try {
                $response = Service::submitOrder($params);

            } catch (GatewayException $e) {
                throw new \Exception(config('app_debug') ? $e->getMessage() : "支付失败，请稍后重试");
            }
        } else {
            throw new \Exception("请在后台安装配置微信支付宝整合插件");
        }
        return $response;
    }


    /**
     * @ DateTime 2021-06-01
     * @ 订单结算
     * @param string $order_sn      订单号
     * @param float  $payamount     支付金额
     * @param string $transactionid 流水号
     * @return bool
     */
    public static function settle($order_sn, $payamount, $transactionid = '',$paytype)
    {
        $order = self::where('order_sn', $order_sn)->find();

        if (!$order || $order->pay_status == 1) {
            return false;
        }

        if ($payamount != $order->saleamount) {
            \think\Log::write("[shop][pay][{$order_sn}][订单支付金额不一致]");
            return false;
        }
        $order_end_time = \app\common\model\Config::get(['name'=>'order_end_time'])->value;
        // 启动事务
        Db::startTrans();
        try {

            $order->pay_status = 1;
            $order->transactionid = $transactionid;
            $order->payamount = $payamount;
            $order->pay_time = time();
            $order->endtime = time()+$order_end_time*60;
            $order->paytype = $paytype;
            $order->save();

            $order_list = \app\api\model\Order::where('id','in',$order->order_id)->select();
            foreach ($order_list as $k=>$v){
                Order::settle($v['order_sn'],$v['saleamount'],$transactionid,$order->paytype,$order->endtime);
            }
            if ($paytype=='balance'){
                \app\common\model\User::money(-$payamount,$order->user_id,'订单付款,编号:'.$order_sn);
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            //dump($e->getMessage());
            return false;
        }
        //记录操作
        OrderAction::push($order_sn, '系统', '订单支付成功');

        return true;
    }
}